<template>
  <div>
      <!-- 面包屑导航区域 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                :closable="false"
                show-icon>
            </el-alert>

            <!-- 选择商品分类区域 -->
            <el-row class="card_row">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 选择商品的级联选择器 -->
                    <el-cascader
                        expand-trigger="hover"
                        :options="cateList"
                        v-model="currentCate"
                        @change="handleChange"
                        :props="cascProps">
                    </el-cascader>
                </el-col>
            </el-row>

            <!-- tabs页签区域 -->
            <el-tabs 
             v-model="activeName" @tab-click="handleTabClick">

                <!-- 动态参数板块内容 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button 
                     type="primary" 
                     size="mini" 
                     :disabled="isBan"
                     @click="addData">添加参数</el-button>
                    <!-- 动态参数表格区域 -->
                    <el-table
                     :data="ManyTableData"
                     style="width: 100%"
                     border stripe>
                     <!-- 展开行 -->
                        <el-table-column 
                         width="50px" 
                         type="expand"
                        >
                            <template scope="{row}">
                                <el-tag
                                :key="index"
                                v-for="(tag,index) in row.attr_vals"
                                closable
                                :disable-transitions="false"
                                @close="delTag(row,index)">
                                {{tag}}
                                </el-tag>
                                <el-input
                                v-if="row.isTagShow"
                                class="input-new-tag"
                                v-model.trim="row.addValTag"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="addTag(row)"
                                @blur="addTag(row)"
                                >
                                </el-input>
                                <el-button 
                                v-else 
                                class="button-new-tag" size="small" 
                                @click="showInput(row)">+ New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column 
                        width="50px"  
                        type="index" 
                        label="#">
                        </el-table-column>
                        <el-table-column
                            prop="attr_name"
                            label="参数名称">
                        </el-table-column>
                        <el-table-column
                            label="操作">
                            <template scope="{row}">
                                <el-button 
                                type="primary"
                                size="mini"
                                @click="editData(row)">编辑</el-button>
                                <el-button 
                                type="danger"
                                size="mini"
                                @click="delData(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>

                <!-- 静态属性板块内容 -->
                <el-tab-pane 
                label="静态属性" 
                name="only">
                    <el-button 
                    type="primary" 
                    size="mini" 
                    :disabled="isBan"
                    @click="addData">添加属性</el-button>

                    <!-- 静态属性表格区域 -->
                    <el-table
                     :data="OnlyTableData"
                     style="width: 100%"
                     border stripe>
                        <el-table-column 
                         width="50px" 
                         type="expand"
                        >
                            <template scope="{row}">
                                <el-tag
                                :key="index"
                                v-for="(tag,index) in row.attr_vals"
                                closable
                                :disable-transitions="false"
                                @close="delTag(row,index)">
                                {{tag}}
                                </el-tag>
                                <el-input
                                v-if="row.isTagShow"
                                class="input-new-tag"
                                v-model.trim="row.addValTag"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="addTag(row)"
                                @blur="addTag(row)"
                                >
                                </el-input>
                                <el-button 
                                v-else 
                                class="button-new-tag" size="small" 
                                @click="showInput(row)">+ New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column width="50px"  type="index" label="#">
                        </el-table-column>
                        <el-table-column
                            prop="attr_name"
                            label="属性名称">
                        </el-table-column>
                        <el-table-column
                            label="操作">
                            <template scope="{row}">
                                <el-button 
                                type="primary"
                                size="mini"
                                @click="editData(row)">编辑</el-button>
                                <el-button 
                                type="danger"
                                size="mini"
                                @click="delData(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加dialog对话框 -->
        <el-dialog
         :title="'添加'+titleText"
         :visible.sync="isAddData"
         :modal-append-to-body="false"
         width="40%"
         @close="closeAddDataDialog"
            >
            <el-form 
             :model="addFormData"
             ref="addFormRef"
             label-width="100px"
             :rules="addFormRules">
                <el-form-item 
                 :label="titleText" 
                 prop="attr_name">
                    <el-input v-model="addFormData.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="isAddData = false">取 消</el-button>
                <el-button type="primary" @click="addDataCommit">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 编辑dialog对话框 -->
        <el-dialog
         :title="'编辑'+titleText"
         :visible.sync="isEditData"
         :modal-append-to-body="false"
         width="40%"
         @close="closeEditDataDialog"
            >
            <el-form 
             :model="editFormData"
             ref="editFormRef"
             label-width="100px"
             :rules="editFormRules">
                <el-form-item 
                 :label="titleText" 
                 prop="attr_name">
                    <el-input v-model="editFormData.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="isEditData = false">取 消</el-button>
                <el-button type="primary" @click="editDataCommit">确 定</el-button>
            </div>
        </el-dialog>
  </div>
</template>

<script>
export default {
    name:'Params',
    data(){
        return {
            // 获取到的商品分类列表，用于在级联选择器中展示
            cateList:[],
            // 选择商品分类后的双向数据绑定
            currentCate:[],
            // 级联选择器的配置对象
            cascProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            // tabs双向绑定的数据
            activeName:'many',
            // 获取到的对应的板块内数据
            // 动态参数板块的数据
            ManyTableData:[],
            // 静态属性板块的数据
            OnlyTableData:[],
            // 控制添加dialog对话框的显示与隐藏
            isAddData:false,
            // 控制添加对话框中form表单数据对象
            addFormData:{
                attr_name:''
            },
            // 控制添加对话框中的表单验证规则对象
            addFormRules:{
                attr_name:[
                        {
                        required:true,
                        message:'输入不能为空！',
                        trigger:'blur',
                    },
                ]
            },

            // 控制编辑对话框对应的数据
            // 控制编辑dialog对话框的显示与隐藏
            isEditData:false,
            // 控制编辑表单绑定的数据对象
            editFormData:{
                attr_name:''
            },
            // 控制编辑表单的校验规则对象
            editFormRules:{
                attr_name:[
                        {
                        required:true,
                        message:'输入不能为空！',
                        trigger:'blur',
                    },
                ]
            },
            // 获取当前点击的对应表格的id
            currentPropId:0,


            // tag相关
            // 存储new tag是input还是tag
            isTagShow:false,
            // 控制对应参数添加tag的表单数据
            addValTag:''
            
        }
    },
    computed:{
        // 判断是否为三级分类
        // 定义一个计算属性，该属性的结果由当前选中的级联选择器是否为三级分类决定
        isBan(){
            return this.currentCate.length!==3 ? true:false;
        },

        // 当前选中的商品分类的id
        cateId(){
            return this.currentCate.length!==3 ? null : this.currentCate[2];
        },
        // 获取到dialog对话框的标题
        titleText(){
            if(this.activeName === "many"){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }
    },
    methods: {
        // 获取所有商品分类
        async getCateList(){
            const {data:res} = await this.$axios.get('categories');
            if(res.meta.status!==200) return this.$message.error(res.meta.msg);
            this.cateList = res.data;
            console.log(this.cateList);
        },
        // 选择具体商品分类后触发的事件
        handleChange(){
            this.getParamsData();
        },
        // 当用户切换tabs页签功能区时调用该方法
        handleTabClick(){
            this.getParamsData();
        },
        // 发起请求获取对应分类ID的相关参数
        async getParamsData(){
            // 判断如果级联选择器选中的不是三级分类，就重新赋值空数组
            if(this.currentCate.length!==3){
                this.$message.error('不允许使用非3级商品分类');
                this.currentCate = [];
                this.ManyTableData = [];
                this.OnlyTableData = [];
                return;
            }
            // 证明选中了三级分类，这时发起请求
            const {data:res} = await this.$axios.get(`categories/${this.cateId}/attributes`,{
                params:{
                    sel:this.activeName
                }
            })
            if(res.meta.status!==200) return this.$message.error(res.meta.msg);

            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
                item.isTagShow = false;
                item.addValTag = '';
            });
            console.log(res.data);
            // 判断当前选中的是动态参数还是静态属性板块，赋值到对应的板块对应的数组中
            if(this.activeName == "many"){
                this.ManyTableData = res.data
                console.log("Many",this.ManyTableData);
            }else{
                this.OnlyTableData = res.data;
                console.log("Only",this.OnlyTableData);
            }
        },
        // 监听用户单击（动态参数）添加参数按钮
        addData(){
            this.isAddData = true;
        },
        // 监听确认添加数据后
        addDataCommit(){
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid) return this.$message.error('表单格式有误！')

                // 表单校验成功，发起请求
                const {data:res} = await this.$axios.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addFormData.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status!==201) return this.$message.error(res.meta.msg);
                
                this.$message.success(res.meta.msg)
                this.getParamsData()

                this.isAddData = false;
            })
        },
        // 监听用户关闭dialog对话框时
        closeAddDataDialog(){
            this.$refs.addFormRef.resetFields()
        },

        // 点击编辑后，展示dialog对话框
        editData(row){
            console.log(row);
            this.currentPropId = row.id
            this.isEditData = true
        },
        // 监听关闭编辑功能对话框时
        closeEditDataDialog(){
            // 重置表单
            this.$refs.editFormRef.resetFields();
        },
        // 监听编辑功能点击确认提交后
        editDataCommit(){
            this.$refs.editFormRef.validate(async valid=>{
                if(!valid) return this.$message.error('表单格式有误！')
                
                const {data:res} = await this.$axios.put(`categories/${this.cateId}/attributes/${this.currentPropId}`,{
                    attr_name:this.editFormData.attr_name,
                    attr_sel:this.activeName,
                })
                if(res.meta.status!==200) return this.$message.error(res.meta.msg);

                this.$message.success(res.meta.msg);
                this.getParamsData();
                this.isEditData = false
            })
        },
        // 删除对应表格中的数据
        delData(row){
            this.$messageBox.confirm('此操作将永久删除该属性, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(async () => {
                    // 点击确定后发起请求删除属性
                    const {data:res} = await this.$axios.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
                    // 状态码不为200则删除失败，提示错误信息
                    if(res.meta.status!==200){
                       return this.$message.error(res.meta.msg);
                    }
                    // 删除成功后刷新属性列表
                    this.getParamsData()
                    // 提示删除成功
                    this.$message({
                        type: 'success',
                        message: res.meta.msg
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
        },
        // 添加标签或删除标签的请求
        async updataTag(row){

            const {data:res} = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals:row.attr_vals.join(' ')
            })

            if(res.meta.status!==200) return this.$message.error(res.meta.msg);
            
            this.$message.success(res.meta.msg);
        },
        // 监听用户单击关闭对应参数的对应tag
        delTag(row,index){
            row.attr_vals.splice(index,1);
            this.updataTag(row);
        },
        // 监听用户编辑添加new tag时
        showInput(row){
            row.isTagShow = true;
            this.$nextTick(_=>{
                this.$refs.saveTagInput.focus();
            })
        },
        // 监听用户取消tag标签中input焦点时
        addTag(row){
            if(row.addValTag.length === 0){
                row.addValTag = ''
                row.isTagShow = false;
                return
            }
            row.attr_vals.push(row.addValTag)
            row.addValTag = '';
            row.isTagShow = false;

            this.updataTag(row);
        }
        
    },
    created() {
        this.getCateList()
    },
}
</script>

<style lang="less" scoped>
.card_row{
    margin: 15px 0;
}
.left{
    margin-left: 50px;
}
.el-tag{
    margin: 10px;
}
.button-new-tag{
    margin-left:10px;
}
.input-new-tag {
    width: 120px;
    margin-left: 10px;
}
</style>